
var openTitle = function(option){
	mui.openWindowWithTitle({
	    url: option.url,
	     id: (option.id).split('/').slice(-1)[0],
	    extras:option.extras,
	    show:option.show,
	    waiting:option.waiting
	},{
		backgroundColor:"#fff",//导航栏背景色
	    title:{//标题配置
	        text: option.title,//标题文字
	        styles:{
	        	color:"#f48041",
	        }
	    },
	    back:{//左上角返回箭头
	        image:{
	            base64Data:''
	        },
			click:option.back_click,
	    }
	})
}

function getHttp(url,token) {
	if(token) {
		return getHttpHost() + url + '/token/' + getuid('uid');
	}
	else {
		
		return getHttpHost() + url
	}

}

mui('body').on('tap','a[href]',function(){
	var href   = this.getAttribute('href'),
		title  = this.getAttribute('title'),
		dataid = this.getAttribute('data-id'),
		noShow = this.getAttribute('no-show');
		console.log('noShow:'+noShow)
	if(!(href.indexOf(':')+1) && href!='#'){
		if(!dataid){
			dataid='';
		}
		openTitle({
			title: title,			
			url:href,
			id: href,
			extras:{
				comeFrom:plus.webview.currentWebview().id,
				dataid:dataid,
			},
			show:{
				autoShow:noShow?false:true,
			},
			waiting:noShow?{
					options:{
					back:'none',
				}
			}:{}
		})
	}
})


//login

//拼接路径
var get_path_length = function(){
	var root = window.location.href.split('HBuilder/www/').slice(-1)[0]
	var length = root.split('/').length-2 
	var path = ''
	if(length<0){
		path = 'view/' //view/login/login.html
	}
	else{
		for (var i=length ; i>0 ; i--) {
			path+='../'  //../login/login.html
		}
	}
	return path
}

//刷新页面
document.addEventListener('page-reload',function(){
	//console.log(JSON.stringify(plus.webview.currentWebview()));
	//console.log('reload');
	plus.webview.currentWebview().reload();
});

//刷新顶层购物车
var refresh_shopcart = function() {
	mui.fire(plus.webview.getWebviewById('trolley.html'),'page-reload');
};

//登录访问控制
var login_lock = function(e_target,e_name,e_argm){
		mui.plusReady(function(){
			//console.log(JSON.stringify(e_argm));
			var token_time=getuid('expire_time')*1000;
			var token_date=new Date();
			var now_time=Date.parse(token_date);

			if(localStorage.getItem('uid') && token_time>now_time){
				mui.fire(plus.webview.getWebviewById(e_target),e_name,e_argm)
			}
			else{
				openTitle({
					title:'登录',
					url:get_path_length()+'login/login.html',
					id:'login.html',
					extras:{
						'e_target': e_target,
						'e_name'  : e_name,
						'e_argm'  : e_argm
					}
				})
			}
	});
	
};

var login_suc = function(d){
	
	window.localStorage.setItem('head',d.data.userpic?d.data.userpic:'');
 	window.localStorage.setItem('uid',d.data.user_token);
    window.localStorage.setItem('nickname',d.data.nickname); 
    window.localStorage.setItem('expire_time',d.data.expire_time)
    window.localStorage.setItem('points',d.data.points);
    window.localStorage.setItem('username',d.data.username);
    window.localStorage.setItem('address_id',d.data.address_id);
    window.localStorage.setItem('coin',d.data.coin);
     window.localStorage.setItem('sex',d.data.sex);
	call_reload()
}

var login_out = function(){
	window.localStorage.removeItem('head');
 	window.localStorage.removeItem('uid'); 
    window.localStorage.removeItem('nickname');
    window.localStorage.removeItem('points'); 
    window.localStorage.removeItem('expire_time'); 
    window.localStorage.removeItem('username');
    window.localStorage.removeItem('address_id');
    window.localStorage.removeItem('coin');
    window.localStorage.removeItem('area_id');
     window.localStorage.removeItem('sex');
	call_reload()
}

var call_reload = function(){
	var all = plus.webview.all()
	all.forEach(function(item){
		mui.fire(item,'page-reload',null)
	})
};


var check_login = function(){
	if(localStorage.getItem('uid')) return true
	else return false
};

var getCurrentId = function(){
	return plus.webview.currentWebview().id
}

//计时器
var timer = function(end_time,call_back,end_call_back){
	var intv = null,
		_timer = {
			rest: end_time > Date.now() ? end_time - Date.now() : 0,
			getH : function(show_zero){
				var num = ~~(this.rest/60/60/1000)
				if(show_zero){
					num = num < 10 ? '0'+num : num
				}
				return num
			},
			getM : function(show_zero){
				var num = ~~(this.rest/60/1000)%60
				if(show_zero){
					num = num < 10 ? '0'+num : num
				}
				return num
			},
			getS : function(show_zero){
				var num = ~~(this.rest/1000)%60
				if(show_zero){
					num = num < 10 ? '0'+num : num
				}
				return num
			},
			stop : function(){
				intv = null
			}
		}
	
	call_back(_timer);	//开始时执行一次
	
	intv = setInterval(function(){
		_timer.rest = end_time - Date.now()
		if(_timer.rest <= 0){
			_timer.rest = 0
			call_back(_timer)	//结束时执行一次
			//计时结束回调
			if(typeof end_call_back == 'function'){
				end_call_back()
			}
			
			clearInterval(intv)
		}
		else{
			call_back(_timer)	//常规执行
		}
	},500)
}

//选择器日期生成器
var create_pickerdata = function(){
	var pickerdata = [],
		days = 5, 	//送货天数
		time_slot = [
		{ value : 01,text:'00:00~02:00', },
		{ value : 02,text:'02:00~04:00', },
		{ value : 03,text:'04:00~06:00', },
		{ value : 04,text:'06:00~08:00', },
		{ value : 05,text:'08:00~10:00', },
		{ value : 06,text:'10:00~12:00', },
		{ value : 07,text:'12:00~14:00', },
		{ value : 08,text:'14:00~16:00', },
		{ value : 09,text:'16:00~18:00', },
		{ value : 10,text:'18:00~20:00', },
		{ value : 11,text:'20:00~22:00', },
		{ value : 12,text:'22:00~24:00', }
	]
	
	var now = new Date()
	
	//大于23:30时算作明天0:00
	if(now.getHours() >= 23 && now.getMinutes() >= 30){
		now.setDate(now.getDate()+1)
		now.setHours(0)
		now.setMinutes(0)
	}
	
	//计算今天的可用时间段，截取自time_slot
	var over_hour = now.getMinutes()>=30?1:0
	var today_time_slot = time_slot.slice(~~((now.getHours() + over_hour)/2) - 12)
	
	for(var i = 0;i<days;i++){
		var today = new Date()
		today.setDate(today.getDate()+i)
		
		pickerdata.push({
			value : today.getFullYear()+'年'+(today.getMonth()+1)+'月'+today.getDate()+'日',
			text  :(today.getMonth()+1)+'月'+today.getDate()+'日',
			children : (i==0?today_time_slot:time_slot)
		})
	}
	
	return pickerdata
}

//日历生成器
var create_calendar = function(signed){
	//日历HTML表格
	var calendar = ''
	
	//已签到日期
	
	
    var i, k,
    today = new Date(),
    y = today.getFullYear(),
    m = today.getMonth(),
    d = today.getDate(),
    firstday = new Date(y, m, 1),
    
    //判断第一天是星期几(返回[0-6]，0代表星期天，1代表星期一)
    dayOfWeek = firstday.getDay()==6?0:firstday.getDay()+1,
    
    //当月共几天
    days_per_month = new Date(y,m+1,0).getDate(),
    
    //确定行数
    str_nums = Math.ceil((dayOfWeek + days_per_month) / 7);
    
    //打印表格第一行(显示星期)
    calendar+='<table border="0"><tr><th>六</th><th>日</th><th>一</th><th>二</th><th>三</th><th>四</th><th>五</th></tr>';
    
    //二维数组创建日期表格
    for (i = 0; i < str_nums; i += 1) {
	    calendar+='<tr>';
	    for (k = 0; k < 7; k++) {
	    	var idx = 7 * i + k;				//为每个表格创建索引,从0开始
	    	var date = idx - dayOfWeek + 1;		//将当月的1号与星期进行匹配
	    	(date <= 0 || date > days_per_month) ? date = '&nbsp;': date = idx - dayOfWeek + 1;    //索引小于等于0或者大于月份最大值就用空表格代替
	    	//高亮显示当天
	    	if(date == d && signed.indexOf(date)+1){
	    		calendar+='<td><span class="today signed">' + date + '</span></td>'
	    	}
	    	else if(date == d){
	    		calendar+='<td><span class="today">' + date + '</span></td>'
	    	}
	    	else if(signed.indexOf(date)+1){
	    		calendar+='<td><span class="signed">' + date + '</span></td>'
	    	}
	    	else{
	    		calendar+='<td><span>' + date + '</span></td>'
	    	}
		}
		calendar+='</tr>';
	}
	calendar+='</table>';
   
	return calendar
}

//日期时间格式化输出
Date.prototype.format = function(format) {
	var date = {
		"M+": this.getMonth() + 1,
		"d+": this.getDate(),
		"h+": this.getHours(),
		"m+": this.getMinutes(),
		"s+": this.getSeconds(),
		"q+": Math.floor((this.getMonth() + 3) / 3),
		"S+": this.getMilliseconds()
	};
	if (/(y+)/i.test(format)) {
		format = format.replace(RegExp.$1, (this.getFullYear() + '').substr(4 - RegExp.$1.length));
	}
	for (var k in date) {
		if (new RegExp("(" + k + ")").test(format)) {
			format = format.replace(RegExp.$1, RegExp.$1.length == 1
				? date[k] : ("00" + date[k]).substr(("" + date[k]).length));
		}
	}
	return format;
}

//打开软键盘
var nativeWebview, imm, InputMethodManager;
var initNativeObjects = function() {
    if (mui.os.android) {
        var main = plus.android.runtimeMainActivity();
        var Context = plus.android.importClass("android.content.Context");
        InputMethodManager = plus.android.importClass("android.view.inputmethod.InputMethodManager");
        imm = main.getSystemService(Context.INPUT_METHOD_SERVICE);
    } else {
        nativeWebview = plus.webview.currentWebview().nativeInstanceObject();
    }
};
var showSoftInput = function() {
    if (mui.os.android) {
        imm.toggleSoftInput(0, InputMethodManager.SHOW_FORCED);
    } else {
        nativeWebview.plusCallMethod({
            "setKeyboardDisplayRequiresUserAction": false
        });
    }
       //此处可写具体逻辑设置获取焦点的input
       var inputElem = document.querySelector('#comment-input');
              inputElem.focus(); 
};

var showWindow = function(){
	mui.currentWebview.show('slide-in-right', 300);
	plus.nativeUI.closeWaiting();
}
